<?php
    //If you want to navigate to a page then change this variable
    $settingPage = 0;
?>
<?php $title = "Management Panel"; ?>
<?php include_once("header.php"); ?>
<?php
    if(!$page->hasAccess())
    {
        Core::redirect("index.php");
    }
    $panel = new AdminController($personId);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (isset($_POST["formSource"])) {
            switch ($_POST["formSource"]) {
                case "cAccount":
                    $pId = ($_POST["person"] == "null" ? null : $_POST["person"]);
                    if($_POST["action"]=="delete")
                    {
                        $res = Person::delete($pId);
                        if($res=="true")
                        {
                            $page->addMessage("Person Deleted!");
                        }
                        else
                        {
                            $page->addMessage($res);
                        }
                    }
                    else
                    {
                        $firstName = Core::sanitize($_POST["firstName"]);
                        $lastName = Core::sanitize($_POST["lastName"]);
                        $accountType = $_POST["accountType"];
                        $contactNumber = Core::sanitize($_POST["contactNumber"]);
                        $email = Core::sanitize($_POST["email"]);
                        $skills = Core::sanitize($_POST["skills"]);
                        $gender = $_POST["gender"];
                        $address = Core::sanitize($_POST["address"]);
                        $staffId = Core::sanitize($_POST["staffId"]);
                        $activated = Core::sanitize(($_POST["activated"] == "true" ? 1 : 0));
                        //$personId,$accountType,$firstName,$lastName,$email,$skills,$gender,$contactNumber,$address
                        if ($pId != null) {
                            $panel->updateUser($pId, $accountType, $firstName, $lastName, $email, $skills, $gender, $contactNumber, $address, $activated);
                            if($staffId!=null || $staffId!="")
                            {
                                $panel->updateStaffId($pId,$staffId);
                            }
                            $page->addMessage("User Profile Updated!");
                        } else {
                            $password = Core::sanitize($_POST["newPassword"]);
                            //$firstName,$lastName,$email,$password,$gender,$contactNumber,$accountType=ACC_VOLUNTEER
                            $reg = new RegisterController($firstName, $lastName, $email, $password, $gender, $contactNumber, $accountType);
                                switch($reg->register())
                                {
                                    case REGISTER_SUCCESS : 
                                        $panel->update($reg->getId(),P_SKS,$skills);
                                        $panel->update($reg->getId(),P_ADD,$address);
                                        $panel->update($reg->getId(),P_ACT,$activated);
                                        $panel->update($reg->getId(),P_AT,$accountType);
                                        $panel->update($reg->getId(),P_UI,$staffId);
                                        $page->addMessage("User Created");
                                    break;
                                    case REG_ERR : 
                                        $page->addMessage("User Creation failed (INSERT ERROR)");
                                    break;
                                    case REG_ERR_EMAIL : 
                                        $page->addMessage("Email Already Exists!");
                                    break;
                                }
                        }
                    }
                    
                    $settingPage = 4;
                    break;
                case "cEvent":
                    $eventId = ($_POST["event"] == "null" ? null : $_POST["event"]);

                    if($_POST["action"]=="delete")
                    {
                        EventController::delete($eventId);
                        $page->addMessage("Event Deleted!");
                    }
                    else
                    {
                        $eventName = Core::sanitize($_POST["eventName"]);
                        $description = Core::sanitize($_POST["eventDescription"]);
                        $startTime = Core::sanitize($_POST["eventStartTime"]);
                        $endTime = Core::sanitize($_POST["eventEndTime"]);
                        $startDate = Core::sanitize($_POST["eventStartDate"]);
                        $endDate = Core::sanitize($_POST["eventEndDate"]);
                        $carpoolTime = Core::sanitize($_POST["carPoolTime"]);
                        $locationDetails = Core::sanitize($_POST["locationDetails"]);
                        $meetingLocation = Core::sanitize($_POST["meetingLocation"]);
                        $meetingTime = Core::sanitize($_POST["meetingTime"]);
                        $carpoolLocation = Core::sanitize($_POST["carPoolLocation"]);
                        $m1 = (isset($_POST["manager1"]) ? $_POST["manager1"] : "null");
                        $m2 = (isset($_POST["manager2"]) ? $_POST["manager2"] : "null");
                        $m3 = (isset($_POST["manager3"]) ? $_POST["manager3"] : "null");
                        $m4 = (isset($_POST["manager4"]) ? $_POST["manager4"] : "null");
                        $m5 = (isset($_POST["manager5"]) ? $_POST["manager5"] : "null");
                        if (is_null($eventId)) {
                            //Create Event
                            //$eventName,$startTime,$endTime,$startDate,$endDate,$meetingLocation,$locationDetails=null,$carpoolTime=null,$manager=null
                            $event = new CreateEvent($eventName, $description, $startTime, $endTime, $startDate, $endDate, $meetingLocation, $meetingTime, $locationDetails, $carpoolTime, $carpoolLocation, $m1, $m2, $m3, $m4, $m5);
                            if ($event->register()) {
                                $page->addMessage("Event Created!");
                            } else {
                                $page->addMessage("Event Creation Failed!");
                            }
                        } else {
                            Event::updateEvent($eventId, $eventName, $description, $startTime, $endTime, $startDate, $endDate, $meetingLocation, $meetingTime, $locationDetails, $carpoolTime, $carpoolLocation, $m1, $m2, $m3, $m4, $m5);
                            $page->addMessage("Event Updated!");
                        }
                    }

                    $settingPage = 0;
                    break;
                case "cActivity" :
                    $activityId = ($_POST['activity'] == "null" ? null : $_POST['activity']);
                    if($_POST["action"]=="delete")
                    {
                        ActivityController::delete($activityId);
                        $page->addMessage("Activity Deleted!");
                    }
                    else
                    {
                        $title = $_POST["activityTitle"];
                        $description = $_POST["activityDescription"];
                        $startTime = $_POST["activityStartTime"];
                        $endTime = $_POST["activityEndTime"];
                        $startDate = $_POST["activityStartDate"];
                        $endDate = $_POST["activityEndDate"];
                        $eventId = $_POST['activityEvent'];
                        //$title,$startTime,$endTime,$startDate,$endDate,$description,$event
                        if (is_null($activityId)) {

                            $activity = new CreateActivity($title, $startTime, $endTime, $startDate, $endDate, $description, $eventId);
                            if ($activity->register()) {
                                $page->addMessage("Activity Created");
                            } else {
                                $page->addMessage("Activity Creation failed!");
                            }
                        } else {
                            Activity::updateActivity($activityId, $title, $startTime, $endTime, $startDate, $endDate, $description, $eventId);
                            $page->addMessage("Activity Updated!");
                        }
                    }
                    
                    $settingPage = 1;
                    break;

                case "cRole" :
                    $roleId = ($_POST["role"] == "null" ? null : $_POST["role"]);
                    if($_POST["action"]=="delete")
                    {
                        RoleController::delete($roleId);
                        $page->addMessage("Role Deleted!");
                    }
                    else
                    {
                        $title = $_POST["roleTitle"];
                        $description = $_POST["roleDescription"];
                        $startTime = $_POST["roleStartTime"];
                        $endTime = $_POST["roleEndTime"];
                        $startDate = $_POST["roleStartDate"];
                        $endDate = $_POST["roleEndDate"];
                        $positions = $_POST["positions"];
                        $activityId = $_POST['roleActivity'];
                        $skills = $_POST['skills'];
                        $payRate = $_POST['payRate'];
                        if (is_null($roleId)) {
                            //$title,$startTime,$endTime,$startDate,$endDate,$description,$event
                            $role = new CreateRole($title, $description, $startTime, $endTime, $startDate, $endDate, $payRate, $positions, $skills, $activityId);
                            if ($role->register()) {
                                $page->addMessage("Role Created");
                            } else {
                                $page->addMessage("Role Creation failed!");
                            }
                        } else {
                            Role::updateRole($roleId, $title, $description, $startTime, $endTime, $startDate, $endDate, $payRate, $positions, $skills, $activityId);
                            $page->addMessage("Role Updated!");
                        }
                    }

                    $settingPage = 2;
                    break;
                case "resetPassword" :
                    $resetPassword = $_POST["password"];
                    $pId = $_POST["person"];
                    $panel->resetPassword($pId, $resetPassword);
                    $page->addMessage("Password Reset Successful");
                    $settingPage = 5;
                    break;
                case "cUniversity":
                    $id = Core::sanitize($_POST["person"]);
                    $studentNumber = Core::sanitize($_POST["universityId"]);
                    $degreeName = Core::sanitize($_POST["degreeName"]);
                    $majors = Core::sanitize($_POST["major"]);
                    $yod = Core::sanitize($_POST["year"]);
                    $entryToUts = Core::sanitize($_POST["entry"]);
                    $highSchool = Core::sanitize($_POST["highSchool"]);
                    $eca = Core::sanitize($_POST["extraCurricular"]);
                    $scholarShips = Core::sanitize($_POST["scholarships"]);
                    $previousInternships = Core::sanitize($_POST["intership"]);
                    $internshipOrganized = ($_POST["internOrganised"] == "true" ? 1 : 0);
                    $panel->updateUniversityDetails($id, $studentNumber, $degreeName, $majors, $yod, $entryToUts, $highSchool, $eca, $scholarShips, $previousInternships, $internshipOrganized);
                    $page->addMessage("University Details Updated!");

                    $settingPage = 6;
                    break;
                case "cOther":
                    $id = Core::sanitize($_POST["person"]);
                    $availaibity = Core::sanitize($_POST["availability"]);
                    $workshops = Core::sanitize($_POST["workshops"]);
                    $driversLicence = $_POST["licence"];
                    $refugee = $_POST["refugee"];
                    $indigenous = $_POST["indigenous"];
                    $paperwork = Core::sanitize($_POST["paperwork"]);
                    $contract = Core::sanitize($_POST["contract"]);
                    $offer = $_POST["offer"];
                    $panel->updateOtherDetails($id, $availaibity, $workshops, $driversLicence, $refugee, $indigenous, $paperwork, $contract, $offer);
                    $page->addMessage("Other details Updated!");

                    $settingPage = 7;
                    break;
                case "cApplicant":
                    $roleId = $_POST["applicantRole"];
                    $applicantId = $_POST["person"];
                    $accepted = $_POST["accepted"];
                    $oldaccepted = Role::getAccepted($roleId, $applicantId);
                    $hours = Core::sanitize($_POST["hours"]);
                    $attended = ($_POST["attended"] == true ? 1 : 0);
                    $panel->updateRoleApplied($applicantId,$roleId,$accepted,$hours,$attended);
                    if(($oldaccepted=="pending" || $oldaccepted=="rejected") && $accepted == "accepted"){
                        Role::subPosition($roleId,1);
                    }
                    if(($accepted=="pending" || $accepted=="rejected") && $oldaccepted == "accepted"){
                        Role::addPosition($roleId,1);
                    }
                    $page->addMessage("Application Details updated!");

                    $settingPage = 3;
                    break;

            }
        }
    }
?>
<div class="centerContent">
    <label class="pageMessage"><?php $page->printMessages(); ?></label>
    <div id="accountButtons" class="accountButtons">
        <input class="button" type="button" value="Event"/>
        <input class="button" type="button" value="Activity"/>
        <input class="button" type="button" value="Role"/>
        <input class="button" type="button" value="Applicants"/>
        <?php
        if(!$page->isEvtMgr())
        { ?>
        <input class="button" type="button" value="Account Information"/>
        <input class="button" type="button" value="Reset Password"/>
        <input class="button" type="button" value="University"/>
        <input class="button" type="button" value="Others"/>
        <?php
        } ?>
    </div>
    <br/>
    <?php include_once("WEB-INF/event.php"); ?>
    <?php include_once("WEB-INF/activity.php"); ?>
    <?php include_once("WEB-INF/role.php"); ?>
    <?php include_once("WEB-INF/applicants.php"); ?>
    <?php
        if(!$page->isEvtMgr())
        {
            include_once("WEB-INF/account.php");
            include_once("WEB-INF/resetpassword.php");
            include_once("WEB-INF/university.php");
        }
        include_once("WEB-INF/other.php");
    ?>

</div>
<script type="text/javascript">
    var managementPanel = (function() {
        var forms;  //formlist
        var buttons; //tab buttons
        var page = parseInt(<?php echo $settingPage ?>);

        window.addEventListener("load", function() {
            buttons = UTSDK.$("accountButtons");
            forms = document.getElementsByTagName("form");
            forms = [].slice.call(forms);
            forms.splice(0, 1); //remove login form
            //Loop through forms and setup event listeners and popupate selects
            for (var i = 0; i < buttons.children.length; i++) {
                buttons.children[i].addEventListener("click", changeSelected); //change tab
                forms[i].style.display = "none"; //hide form
                if (forms[i].id !== "applicantForm") {
                    //change listener for updating of top select
                    forms[i].elements[2].addEventListener("change", changeField);
                    var json = {};
                    //Get the fields to populate top select
                    json[forms[i].elements[2].name] = "all";
                    json["id"] = forms[i].id;
                    UTSDK.updateSelect(json, forms[i].elements[2], "update.php", function(data){
                        if(data["id"] === "eventForm"){
                            eventForm.showReportBtn();
                        }
                    });
                }
                //Register deletebutton for onclick
                registerDeleteBtn(forms[i]);
            }
            if (page !== null)
                navigate(page);
            else
                navigate(0);

            enableHide();
        });

        function registerDeleteBtn(form) {
            var id = form.id.substring(0, form.id.length - 4);
            var deleteBtn = UTSDK.$(id + "Delete");
            if (deleteBtn) {
                deleteBtn.addEventListener("click", deleteField);
            }
        }

        function navigate(page) {
            UTSDK.addClass(buttons.children[page], "selectedButton");
            forms[page].style.display = "block";
        }

        function changeSelected(evt) {
            var parent = evt.target.parentElement;
            for (var i = 0; i < parent.children.length; i++) {
                if (parent.children[i] === evt.target) {
                    UTSDK.addClass(parent.children[i], "selectedButton");
                    UTSDK.fadeIn(forms[i], 0.7);
                }
                else {
                    UTSDK.removeClass(parent.children[i], "selectedButton");
                    UTSDK.fadeOut(forms[i], 0.7);
                }
            }
        }

        function enableHide() {
            UTSDK.$("accountType").disabled = false;
        }

        //Update form when top select is changed
        function changeField(evt) {
            var form = UTSDK.getNearestParent(evt.target, "FORM");
            var id = form.id.substring(0, form.id.length - 4);
            var submitBtn = UTSDK.$(id + "Submit");
            var deleteBtn = UTSDK.$(id + "Delete");
            //When the top select is changed to create new
            if (evt.target.value === "none" || evt.target.value === "null") {
                submitBtn.value = "Create";
                if (deleteBtn)
                    deleteBtn.style.display = "none";
                else
                    evt.target.setAttribute("data-required", "true");
                form.elements[1].value = "create";
            }
            //Top select is chagned to an existing field
            else {
                submitBtn.value = "Save";
                if (deleteBtn)
                    deleteBtn.style.display = "block";
                else
                    evt.target.setAttribute("data-required", "false");
                form.elements[1].value = "update";
            }
            
            //Update form for change
            var json = {};
            json["formSource"] = form.elements[0].value;
            json[form.elements[2].name] = form.elements[2].value;
            json["id"] = form.id;
            UTSDK.updateForm(json, "update.php", function() {
                if (form.id === "eventForm") {
                    eventForm.updateForm();
                }
            });
        }

        function deleteField(evt) {
            if(confirm('Are you sure you want to delete?')){
                var form = UTSDK.getNearestParent(evt.target, "FORM");
                form.elements["action"].value = "delete";
                form.submit();
            }
        }
    })();
</script>
<?php include_once("footer.php"); ?>